#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

#define NUM 5

//初始化条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
//初始化互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* active(void* args)
{
    string name = static_cast<const char*>(args);

    while(true)
    {
        //上锁
        pthread_mutex_lock(&mutex);
        //条件变量使线程处于阻塞状态
        pthread_cond_wait(&cond, &mutex);

        cout << name << "活动" << endl;

        //解锁
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    //创建线程池
    pthread_t tids[NUM];
    for(int i = 0; i < NUM; i++)
    {
        char* name = new char[32];
        snprintf(name, 32, "thread->%d", i + 1);
        pthread_create(tids + i, nullptr, active, name);
    }

    sleep(2);

    //主进程
    while(true)
    {
        cout << "main thread wakeup thread..." << endl;
        pthread_cond_signal(&cond); //唤醒单个线程
        sleep(1);
    }

    //等待线程池
    for(int i = 0; i < NUM; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    return 0;
}